/**
 * Created by zhangiang on 16/12/8.
 */
import PullRefresh from "../components/mui/PullRefresh";
import NoData from "../components/NoData";

(function(lf,r){
    var log = lf.utils.log,
        ajax = lf.utils.ajax,
        doAction = lf.bridgeJs.doAction,
        appAlert = lf.bridgeJs.alert,
        appConfirm = lf.bridgeJs.confirm,
        flag = lf.utils.getUrlParam('flag',location.search) || 'approving';//approving 待审批/ apply 我发起的

    //字面字符串一定要定义成常量。能否出现多次，改死你！
    const APPROVING = 'approving',
        APPROVED = 'approved',
        APPLY = 'apply';

    var Header = r.createClass({
        getInitialState: function(){
            return{
                headers: [
                    {
                        title:'待审批',
                        type: '1',
                    },
                    {
                        title:'已审批',
                        type: '2',
                    }
                ],
                counts: [],
            }
        },

        componentDidMount: function () {
            var $links = $('.header a'),
                me = this;

            if(!$links.length) return;

            //默认第一个点中
            if(flag == APPROVING)
                $links.eq(0).addClass('active');
            else if(flag == APPROVED)
                $links.eq(1).addClass('active');

            //点击
            $links.each(function (index,link) {
                $(this).on('tap',function(){
                    //切换样式,
                    $(this).addClass('active')
                        .siblings().removeClass('active');

                    //加载数据,默认是第一页的
                    var type = $(this).data('type');
                    flag = type == '1' ? APPROVING : APPROVED;
                    me.props.getList(type, 1, false)
                    // me.props.resetPage(() => );

                }.bind(this));

            });
        },
        render: function () {
            var me = this;

            if(flag != APPLY){
                var headers = this.state.headers.map(function (data,i) {
                    return(
                        <a key={'head-'+i} data-type={data.type} className="item" href="javascript:;" >
                            <p>{me.props.counts[i] || 0}</p>
                            <p className="bold">{data.title}</p>
                            <div className="rectangle"></div>
                        </a>
                    );
                });
            }

            return(
                <div className="header ">
                    <div className={flag != APPLY ? "item-row shot-width" : 'ele-hide'}>
                        {headers}
                    </div>
                    <div className="split-line"></div>
                </div>
            )
        },
    });

    /**
     * props
     *  data
     *  total
     *  getList()
     */
    var Body = r.createClass({
        getInitialState: function(){
            return {
            }
        },
        /**
         * @param valueList 以逗号分隔
         */
        hiddenInputRender: function (valueList) {
            return valueList.split(',').map(function (value, i) {
                return <input type="hidden" value={value} key={'hidden-'+i}/>
            });
        },
        render: function () {
            var list,
                me = this;

            if(!this.props.total)
                return <NoData/>;

            if(flag == APPROVING || flag == APPROVED){
                list = this.props.data.map(function (data, i) {
                    var hiddenInputs = me.hiddenInputRender(data.processId+','+data.taskKey+','+data.orderId),
                        time = flag == lf.approvalInfo.APPROVING ? data.taskCreateTime : data.taskEndTime,
                        stayTime = data.taskVariableMap.stayTime ? '已停留' + data.taskVariableMap.stayTime : '',
                        processName = data.processName+ '(' + data.orderVariableMap.createName + ')',

                        btns = [],
                        recallBtn = <p onTouchEnd={me.operate} data-type="recall" data-taskid={data.taskId} data-orderid={data.orderId} data-processid={data.processId}
                                       className="mui-btn mui-btn-blue">收回</p>,
                        deleteBtn = <p onTouchEnd={me.operate} data-type="delete" data-taskid={data.taskId} data-orderid={data.orderId} data-processid={data.processId}
                                       className="mui-btn mui-btn-red">删除</p>,

                        endBtn = <p onTouchEnd={me.operate} data-type="end"  data-taskid={data.taskId} data-orderid={data.orderId} data-processid={data.processId}
                                    className="mui-btn mui-btn-red">终止</p>,

                        toDetail = <p onTouchEnd={me.operate} data-type="detail" className="mui-btn mui-btn-green">
                            {flag == APPROVING ? '办理' : '查看'}</p>;

                    if(flag == APPROVED){
                        var taskVariable = JSON.parse(data.taskVariable) || {};
                        if(data.operator && data.operator.indexOf(lf.userInfo.id) > -1 && taskVariable.status == 0){
                            if(data.taskId == data.parentId)
                                btns.push(recallBtn)
                            if(data.taskType == 1)
                                btns.push(deleteBtn)
                        }
                    }
                    if(btns.length == 0) btns.push(toDetail);

                    if(flag == APPROVING) btns.push(endBtn);

                    return (
                        <div>
                            <li key={'list-'+i} className="mui-table-view-cell">
                                <a ref="tapNode" className="flex-box-row " href="javascript:;">
                                    <div className="item flex-box-col">
                                        <p className="text-dot">{data.orderVariableMap.title}</p>
                                        <p className="red text-dot">{processName }</p>
                                    </div>
                                    <div className="item flex-box-col">
                                        <p className="gray">{stayTime}</p>
                                        <p className="gray small">{time}</p>
                                    </div>
                                    {hiddenInputs}
                                </a>
                            </li>
                            <div>
                                <div className="btn-box">
                                    {btns}
                                </div>
                                <div className="split-line"></div>
                            </div>
                        </div>
                    )
                });
            }
            //我发起的
            else{
                list = this.props.data.map(function (data,i) {

                    var hiddenInputs = me.hiddenInputRender(data.processId+','+data.taskKey+','+data.orderId),
                        state = data.taskState == 0 ? '已完成' :
                        data.operator + ' (已停留' + data.taskVariableMap.stayTime + ')';

                    return(
                        <li key={'list-'+i} className="mui-table-view-cell">
                            <a ref="tapNode" className="flex-box-row" href="javascript:;">
                                <div className="item flex-box-col">
                                    <p className="text-dot">{data.orderVariableMap.title}</p>
                                    <p className="red">{data.processName}</p>
                                </div>
                                <div className="item flex-box-col">
                                    <p className="small gray">{data.orderCreateTime}</p>
                                    <p className="">{state}</p>
                                </div>
                                {hiddenInputs}
                            </a>
                        </li>
                    )
                });
            }

            return (
                <ul ref="list" className="body mui-table-view lf-list">
                    {list}
                    <li className="mui-table-view-cell" ref="res">
                        <a ref="tapNode" className="flex-box-row" href="javascript:;">
                            <div className="item flex-box-col">
                                <p className="text-dot">张伟的请假</p>
                                <p className="red">事假1</p>
                            </div>
                            <div className="item flex-box-col">
                                <p className="small gray">已停留1小时</p>
                                <p className="">2016 8 21</p>
                            </div>
                        </a>
                    </li>
                </ul>
            );
        },
        componentDidMount(){
           $(r.findDOMNode(this.refs.tapNode)).on('tap',function(e){
             doAction()
               console.log(e.target.parentNode.tagName)
           })

        },
        componentDidUpdate: function () {
            var $links = $(r.findDOMNode(this.refs.list)).find('a');

            $links.off();
            $links.on('tap', (e) => this.toDetail(e));
        },
        operate: function (e) {
            lf.utils.stopBubble(e);
            var $node = $(e.target),
                type = $node.data('type'),
                tip = '你确认要收回吗?',//默认收回
                api = lf.api.workflow.recall;

            if(type == 'detail'){
                this.toDetail($node.parent().parent().siblings().find('a')[0]);
                return;
            }
            else if(type == 'delete') {//删除
                tip = '你确认要删除吗?';
                api = lf.api.workflow.delete;
            }
            else if(type == 'end'){
                tip = '你确认要终止吗?';
                api = lf.api.workflow.startOrExecute;
            }

            var taskId = $node.data('taskid'),
                orderId = $node.data('orderid'),
                processId = $node.data('processid'),
                operate = function () {
                    ajax({
                        type: 'POST',
                        data: {
                            staffId: lf.userInfo.id,
                            taskId: taskId,
                            orderId: orderId,
                            processId: processId,
                            //终止流程会用到
                            taskName: 'end',
                            assignee: 'end',
                            nextOperator: lf.userInfo.id,
                        }
                    },api, function (data) {
                        location.reload();
                    });
                };

            appConfirm(tip, operate);
        },
        /**
         *
         * @param e 事件或者元素
         */
        toDetail: function (e) {
            var node = e.target || e;
            if(node.tagName == 'P'){
                node = $(node).parent().parent();
            }else if(node.tagName == 'DIV'){
                node = $(node).parent();
            }
            else{
                node = $(node);
            }
            //
            var $inputs = node.find('input[type=hidden]'),
                processId = $inputs.eq(0).val(),
                taskName = $inputs.eq(1).val(),
                orderId = $inputs.eq(2).val(),
                url = 'approval-detail.html?processId='+processId+'&taskName='+taskName+'&orderId='+orderId
                    +'&flag='+flag,
                title = '审批详情';

            if(flag == lf.approvalInfo.APPROVED)
                title = '审批详情';
            //log(url)
            doAction(url,title);
        },

    });

    /**
     * props:
     *  user
     *  page
     */
    var Root = r.createClass({
        getInitialState: function(){
            return {
                list: [],
                headerCounts: [0,0],
                currType: 1,
                total: 1, //总数先默认为1
            }
        },
        getHeader(user) {
            ajax({
                data:{
                    staffId: user.id,
                }
            },lf.api.workflow.getCount, (data) => {
                var counts = [];
                counts.push(data.workFlowWaitCount);
                counts.push(data.workFlowAlreadyCount);

                this.setState({
                    headerCounts: counts
                });
            });
        },
        /**
         * @param type 1 待审批; 2 已审批; 3 我发起的
         * @param page 当前第几页
         * @param shouldAppend 是否把新数据追加到原数组中
         */
        getList: function (type,page, shouldAppend) {

            if(!type){
                if(flag == APPROVING){
                    type = 1;
                }
                else if(flag == APPROVED){
                    type = 2;
                }
                else{
                    type = 3;
                }
            }
            if(!page) page = 1;

            var me = this;


            ajax({
                data: {
                    page: page,
                    staffId: lf.userInfo.id,
                    type: type,
                },
                success: function (data) {
                    if(data.code != '200') {
                        appAlert(data.desc);
                        return;
                    }

                    let maxCount = data.maxCount,
                        appendedList = me.state.list;

                    if(me.state.currType == type && shouldAppend) {
                        appendedList.push(...data.dataList);
                    }
                    else {
                        appendedList = data.dataList;
                        mui('#pullrefresh').pullRefresh().refresh(true);
                    }

                    //judge refresh completed, 这句话不能省,每次都要判断
                    mui('#pullrefresh')
                        .pullRefresh()
                        .endPullupToRefresh((appendedList.length == maxCount));

                    me.setState({
                        list: appendedList,
                        currType: type,
                        total: appendedList.length,
                    });
                },
            },lf.api.workflow.approvalList)
        },
        componentWillMount: function () {
            this.getHeader(this.props.user);
            this.getList();

            // lf.appJs.refresh((user) => {
            //     // this.getHeader(user);
            //     // this.getList();
            // })
            lf.appJs.refresh();
        },
        componentWillReceiveProps: function(nextProps){
            var page = nextProps.page;
            this.getList(this.state.currType, page,true)
        },
        render: function () {
            return <div className="approval approval-list">
                <Header  getList={this.getList} counts={this.state.headerCounts}
                         resetPage={this.props.resetPage}/>
                <Body data={this.state.list} getList={this.getList} total={this.state.total}/>
            </div>
        },
    });

    var PullRefreshCon = React.createClass({
        getInitialState: function () {
            return {
                page: 1
            }
        },
        resetPage(cb) {
            this.setState({page: 1}, () => cb());
        },
        pullupFn: function () {
            let newPage = ++this.state.page;
            this.setState({page: newPage});
        },
        render: function () {

            return <PullRefresh pullupFn={this.pullupFn}
                                data={ <Root page={this.state.page}
                                        user={this.props.user}
                                        resetPage={this.resetPage} />
                                     }/>;
        }
    });

    lf.bridgeJs.getUser(function (user) {

        console.log(user)
        r.render(
            <PullRefreshCon user={'user'}/>,
            document.getElementById('root'), function () {
            }
        )
    });
})(liefeng,React)
